package com.heima.schedule.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(Task task) {
        //1.添加任务到数据库中
        Boolean success = addTaskToDB(task);
        //2.添加任务到redis
        if (success) {
            addTaskCache(task);
        }
        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param id 任务id
     * @return
     */
    @Override
    public boolean cancelTask(Long id) {
        boolean flag = false;
        //删除任务,更新任务日志状态
        Task task = updateDb(id, ScheduleConstants.CANCELLED);
        //删除缓存中的任务
        removeTaskFromCache(task);
        flag = true;
        return flag;
    }

    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type     类型
     * @param priority 优先级
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        String key = type + "_" + priority;
        String taskJson = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        if (StringUtils.isNotBlank(taskJson)) {
            Task task = JSON.parseObject(taskJson, Task.class);
            //更新日志数据状态
            updateDb(task.getTaskId(), ScheduleConstants.CANCELLED);
            return task;
        }
        return null;
    }

    /**
     * 删除缓存中的任务
     *
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }


    /**
     * 删除任务,更新任务日志状态
     *
     * @param id     任务id
     * @param status 任务状态
     * @return
     */
    private Task updateDb(Long id, int status) {
        //删除任务
        taskinfoMapper.deleteById(id);
        //更新日志状态
        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(id);
        taskinfoLogs.setStatus(status);
        taskinfoLogsMapper.updateById(taskinfoLogs);
        Task task = new Task();
        BeanUtils.copyProperties(taskinfoLogs, task);
        task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        return task;
    }


    /**
     * 添加任务到redis
     *
     * @param task
     */
    private void addTaskCache(Task task) {
        //构造key
        String key = task.getTaskType() + "_" + task.getPriority();
        //获取5分钟后的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        //判断task存入list还是zset
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            //2.1 如果任务的执行时间小于等于当前时间，存入list
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        }
        //2.2 如果任务的执行时间大于当前时间 && 小于等于预设时间（未来5分钟） 存入zset中
        if (task.getExecuteTime() <= calendar.getTimeInMillis()) {
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }
    }


    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    /**
     * 添加任务到数据库
     *
     * @param task
     * @return
     */
    private Boolean addTaskToDB(Task task) {
        boolean flag = false;
        try {
            //保存任务信息到taskinfo表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            //设置taskId
            task.setTaskId(taskinfo.getTaskId());
            //保存任务信息到taskinfoLogs表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 未来数据定时刷新
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (!StringUtils.isNotBlank(token)) {
            log.info("开始数据定时刷新--定时任务");
            //获取所有未来的定时任务keys
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {
                //按照key的分值查询符合条件的数据
                Set<String> task = cacheService.zRange(futureKey, 0, System.currentTimeMillis());
                //获取当前的key
                String topicKey = futureKey.replace(ScheduleConstants.FUTURE, ScheduleConstants.TOPIC);
                //更新数据
                if (task != null) {
                    cacheService.refreshWithPipeline(futureKey, topicKey, task);
                    log.info("成功的将" + futureKey + "刷新到了" + topicKey);
                }
            }
        }
    }

    /**
     * 数据库任务同步到redis
     */
    @PostConstruct
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){
        //1.清理缓存数据
        clearCache();
        //2.获取5分钟之内的任务
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        //查询所有符合条件的任务
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar));
        //3.新增任务到redis
        for (Taskinfo taskinfo : taskinfos) {
            Task task = new Task();
            BeanUtils.copyProperties(taskinfo,task);
            task.setExecuteTime(taskinfo.getExecuteTime().getTime());
            addTaskCache(task);
        }

        log.info("数据库任务已同步到缓存中");
    }

    /**
     * 清理缓存任务
     */
    private void clearCache() {
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
    }
}
















